<?php

class BusinessController extends CController
{
	const PAGE_SIZE=10;

	/**
	 * @var string specifies the default action to be 'list'.
	 */
	public $defaultAction='register';

	/**
	 * @var CActiveRecord the currently loaded data model instance.
	 */
	private $_model;

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			array('application.filters.LoginFilter +update,my_jiajia'),
		);
	}

	/**
	 * Shows a particular model.
	 */
	public function actionShow()
	{	if(isset($_GET['id'])) $id=$_GET['id'];
		else $id=Yii::app()->session['business_id'];
		if(!isset($id)||$id==null) return;
		
		$model=$this->loadBusiness($id);//厂商信息
		
		$sql="select name from business_sorts where FIND_IN_SET(code,'".implode(',',$model->product_sort)."')";
		$sort_models=Business_sorts::model()->findAllBySql($sql);
		
		$criteria=new CDbCriteria;//产品信息
		$criteria->select='product.*,areas.name as area_name,city.name as city_name,province.name as province_name';
		$criteria->join='INNER JOIN business ON business.id=product.fk_business_id
						 INNER JOIN areas ON business.area=areas.code
						 INNER JOIN areas as city ON left(business.area,4)=city.code
						 INNER JOIN areas as province ON left(business.area,2)=province.code';
		$cond='product.state=0';
		if(isset(Yii::app()->session['business_id'])) $cond.=' and product.fk_business_id='.Yii::app()->session['business_id'];
		$criteria->addCondition($cond);
		$criteria->addCondition('product.fk_business_id='.$id);
		$pages=new CPagination(Product::model()->count($criteria));
		$pages->pageSize=Yii::app()->params['page_size']['user_product_in_business'];
		$pages->applyLimit($criteria);
		$product_models=Product::model()->findAll($criteria);
		
		$this->render('show',array('model'=>$model,'product_models'=>$product_models,'pages'=>$pages,'sort_models'=>$sort_models));
	}
	
	/**
	 * Shows a particular model.
	 */
	public function actionGet_business()
	{	if(isset($_GET['id'])) $id=$_GET['id'];
		if(!isset($id)||$id==null) return;
		
		$model=$this->loadBusiness($id);//厂商信息
		$sql="select name from business_sorts where FIND_IN_SET(code,'".implode(',',$model->product_sort)."')";
		$sort_models=Business_sorts::model()->findAllBySql($sql);
		$this->pageTitle=Yii::app()->name.'-'.$model->name;
		
		$criteria=new CDbCriteria;//产品信息
		$criteria->select='product.*,areas.name as area_name,city.name as city_name,province.name as province_name';
		$criteria->join='INNER JOIN business ON business.id=product.fk_business_id
						 INNER JOIN areas ON business.area=areas.code
						 INNER JOIN areas as city ON left(business.area,4)=city.code
						 INNER JOIN areas as province ON left(business.area,2)=province.code';
		$cond='product.state=0';
		if(isset(Yii::app()->session['business_id'])) $cond.=' and product.fk_business_id='.Yii::app()->session['business_id'];
		$criteria->addCondition($cond);
		$criteria->addCondition('product.fk_business_id='.$id);
		$pages=new CPagination(Product::model()->count($criteria));
		$pages->pageSize=Yii::app()->params['page_size']['product_in_business'];
		$pages->applyLimit($criteria);
		$product_models=Product::model()->findAll($criteria);
		
		$this->render('get_business',array('model'=>$model,'product_models'=>$product_models,'pages'=>$pages,'sort_models'=>$sort_models));
	}
	
	public function actionSearch_by_sort()
	{	
		$this->pageTitle=Yii::app()->name.'-厂家分类搜索';
		if(isset($_POST['product_sort']))$_GET['product_sort']=$_POST['product_sort'];
		if(!isset($_GET['product_sort'])) return;
		$product_sort=$_GET['product_sort'];
		
		$sql="select code,name from business_sorts where code='".substr($product_sort,0,2)."' or code='$product_sort' order by code";
		$sort_models=Business_sorts::model()->findAllBySql($sql);
		
		$criteria=new CDbCriteria;
		$criteria->select='business.*,areas.name as area_name,city.name as city_name,province.name as province_name,count(product.id) as product_sum';
		$criteria->join='INNER JOIN areas ON business.area=areas.code
						 INNER JOIN areas as city ON left(business.area,4)=city.code
						 INNER JOIN areas as province ON left(business.area,2)=province.code
						 LEFT JOIN product ON product.fk_business_id=business.id and product.state=0';
						 	
		$criteria->addCondition('FIND_IN_SET("'.$product_sort.'", business.product_sort)>0');
		$criteria->addCondition('business.state=0');
		$criteria->group='business.id';
		$criteria->order='business.recommend2 desc,business.update_time desc';
		
		$model=Business::model();
		$command=$model->getCommandBuilder();//因group by 查询准确记录数量
		$sql="select count(t.id) from( select business.id FROM business";
		$sql=$command->applyJoin($sql,$criteria->join);
		$sql=$command->applyCondition($sql,$criteria->condition);
		$sql=$command->applyGroup($sql,$criteria->group).") as t";//echo $sql;
		$pages=new CPagination($model->countBySql($sql,$criteria->params));
		$pages->pageSize=Yii::app()->params['page_size']['search_business_by_sort'];
		$pages->applyLimit($criteria);

		$sort=new CSort('Business');
		$sort->applyOrder($criteria);

		$models=$model->findAll($criteria);

		$this->render('search_by_sort',array(
			'models'=>$models,
			'pages'=>$pages,
			'sort'=>$sort,
			'sort_name'=>$sort_models
		));
	}
	
	public function actionSearch_by_area()
	{	
		$this->pageTitle=Yii::app()->name.'-厂家地区搜索';
		if(isset($_POST['area_code']))$_GET['area_code']=$_POST['area_code'];
		if(!isset($_GET['area_code'])) return;
		$area_code=$_GET['area_code'];
		
		if($area_code!=''){
			$sql="select code,name from areas where code='".$area_code."'";
			$area_model=Areas::model()->findBySql($sql);
		}
		else{
			$area_model=new Areas;
			$area_model->name='全部地区';
			$area_model->code='';
		}	
		
		if(isset($_POST['b_name']))$_GET['b_name']=$_POST['b_name'];
		if(isset($_GET['b_name'])&&$_GET['b_name']!='') $b_name=$_GET['b_name'];
		
		$criteria=new CDbCriteria;
		$criteria->select='business.*,areas.name as area_name,city.name as city_name,province.name as province_name,count(product.id) as product_sum';
		$criteria->join='INNER JOIN areas ON business.area=areas.code
						 INNER JOIN areas as city ON left(business.area,4)=city.code
						 INNER JOIN areas as province ON left(business.area,2)=province.code
						 LEFT JOIN product ON product.fk_business_id=business.id and product.state=0';
						 	
		if($area_code!='')
			$criteria->addCondition('left(business.area,2)="'.$area_code.'"');
		if(isset($b_name))	$criteria->addCondition('business.brand like "%'.$b_name.'%"');
		$criteria->addCondition('business.state=0');
		$criteria->group='business.id';
		$criteria->order='business.recommend2 desc,business.update_time desc';
		
		$model=Business::model();
		$command=$model->getCommandBuilder();//因group by 查询准确记录数量
		$sql="select count(t.id) from( select business.id FROM business";
		$sql=$command->applyJoin($sql,$criteria->join);
		$sql=$command->applyCondition($sql,$criteria->condition);
		$sql=$command->applyGroup($sql,$criteria->group).") as t";//echo $sql;
		$pages=new CPagination($model->countBySql($sql,$criteria->params));
		$pages->pageSize=Yii::app()->params['page_size']['search_business_by_area'];
		$pages->applyLimit($criteria);

		$sort=new CSort('Business');
		$sort->applyOrder($criteria);

		$models=$model->findAll($criteria);

		$this->render('search_by_area',array(
			'models'=>$models,
			'pages'=>$pages,
			'sort'=>$sort,
			'area_model'=>$area_model,
			'b_name'=>isset($b_name)?$b_name:''
		));
	}
	
	public function actionSearch_by_brand()
	{	
		if(isset($_POST['b_name']))$_GET['b_name']=$_POST['b_name'];
		if(!isset($_GET['b_name'])) return;
		$b_name=trim($_GET['b_name']);
		
		$criteria=new CDbCriteria;
		$criteria->select='business.*,areas.name as area_name,city.name as city_name,province.name as province_name,count(product.id) as product_sum';
		$criteria->join='INNER JOIN areas ON business.area=areas.code
						 INNER JOIN areas as city ON left(business.area,4)=city.code
						 INNER JOIN areas as province ON left(business.area,2)=province.code
						 LEFT JOIN product ON product.fk_business_id=business.id and product.state=0';
						 	
		if(isset($b_name)&&$b_name!='')
			$criteria->addCondition('business.brand like "%'.$b_name.'%"');
		$criteria->addCondition('business.state=0');
		$criteria->group='business.id';
		$criteria->order='business.recommend2 desc,business.update_time desc';
		
		$model=Business::model();
		$command=$model->getCommandBuilder();//因group by 查询准确记录数量
		$sql="select count(t.id) from( select business.id FROM business";
		$sql=$command->applyJoin($sql,$criteria->join);
		$sql=$command->applyCondition($sql,$criteria->condition);
		$sql=$command->applyGroup($sql,$criteria->group).") as t";//echo $sql;
		$pages=new CPagination($model->countBySql($sql,$criteria->params));
		$pages->pageSize=Yii::app()->params['page_size']['search_business_by_area'];
		$pages->applyLimit($criteria);

		$sort=new CSort('Business');
		$sort->applyOrder($criteria);

		$models=$model->findAll($criteria);

		$this->render('search_by_brand',array(
			'models'=>$models,
			'pages'=>$pages,
			'sort'=>$sort,
			'b_name'=>$b_name
		));
	}
	
	public function actionSearch_by_name()
	{	
		if(isset($_POST['b_name']))$_GET['b_name']=$_POST['b_name'];
		if(!isset($_GET['b_name'])) return;
		$b_name=trim($_GET['b_name']);
		
		$criteria=new CDbCriteria;
		$criteria->select='business.*,areas.name as area_name,city.name as city_name,province.name as province_name,count(product.id) as product_sum';
		$criteria->join='INNER JOIN areas ON business.area=areas.code
						 INNER JOIN areas as city ON left(business.area,4)=city.code
						 INNER JOIN areas as province ON left(business.area,2)=province.code
						 LEFT JOIN product ON product.fk_business_id=business.id and product.state=0';
						 	
		if(isset($b_name)&&$b_name!='')
			$criteria->addCondition('business.name like "%'.$b_name.'%"');
		$criteria->addCondition('business.state=0');
		$criteria->group='business.id';
		$criteria->order='business.recommend2 desc,business.update_time desc';
		
		$model=Business::model();
		$command=$model->getCommandBuilder();//因group by 查询准确记录数量
		$sql="select count(t.id) from( select business.id FROM business";
		$sql=$command->applyJoin($sql,$criteria->join);
		$sql=$command->applyCondition($sql,$criteria->condition);
		$sql=$command->applyGroup($sql,$criteria->group).") as t";//echo $sql;
		$pages=new CPagination($model->countBySql($sql,$criteria->params));
		$pages->pageSize=Yii::app()->params['page_size']['search_business_by_area'];
		$pages->applyLimit($criteria);

		$sort=new CSort('Business');
		$sort->applyOrder($criteria);

		$models=$model->findAll($criteria);

		$this->render('search_by_name',array(
			'models'=>$models,
			'pages'=>$pages,
			'sort'=>$sort,
			'b_name'=>$b_name
		));
	}
	
	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'show' page.
	 */
	public function actionRegister()
	{
		Yii::app()->session['upload_business_times']=0;
		Yii::app()->session['upload_logo_times']=0;
		$model=new Business;
		//地区处理
		$areas['']='请选择';
		$areas_model=Areas::model()->findAllBySql('select * from areas where parent_code="" and state=0');
		foreach($areas_model as $val){
			$areas[$val->code]=$val->name;
		}
		//地区处理
		$sql="select business_sorts.*,sorts.code<>'' as hasChild from business_sorts 
			  left join business_sorts as sorts on sorts.parent_code=business_sorts.code and sorts.state=0 
			  where business_sorts.state=0 group by business_sorts.id";
		$sorts_model=Business_sorts::model()->findAllBySql($sql);//分类处理
		if(isset($_POST['Business']))
		{
			$model->attributes=$_POST['Business'];
			if($model->save()){
				$identity=new UserIdentity($model->username,$model->password);
				$identity->setState('business_id',$model->id);//开始将相关信息写入session
				$identity->setState('linkman',$model->linkman);
				Yii::app()->user->login($identity,0);
				$this->redirect(array('my_jiajia','mess'=>'注册成功!'));
			}
		}
		$this->render('register',array('model'=>$model,'areas'=>$areas,'sorts'=>$sorts_model));
	}
	
	public function actionMy_jiajia(){
		$this->render('my_jiajia');
	}
	
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'show' page.
	 */
	public function actionUpdate()
	{	
		Yii::app()->session['upload_business_times']=0;
		Yii::app()->session['upload_logo_times']=0;
		$id=Yii::app()->session['business_id'];
		$model=$this->loadBusiness($id);
		//地区处理
		$areas['']='请选择';
		$areas_model=Areas::model()->findAllBySql('select * from areas where parent_code="" and state=0');
		foreach($areas_model as $val){
			$areas[$val->code]=$val->name;
		}
		$model->province=substr($model->area,0,2);
		$model->city=substr($model->area,0,4);
		//地区处理
		$sql="select business_sorts.*,sorts.code<>'' as hasChild from business_sorts 
			  left join business_sorts as sorts on sorts.parent_code=business_sorts.code and sorts.state=0 
			  where business_sorts.state=0 group by business_sorts.id";
		$sorts_model=Business_sorts::model()->findAllBySql($sql);//分类处理
		if(isset($_POST['Business']))
		{
			$pics=array('pic1'=>$model->pic1,'pic2'=>$model->pic2,'pic3'=>$model->pic3);
			$logo=$model->logo;
			$model->attributes=$_POST['Business'];
			if($model->save()){
				foreach($pics as $key=>$val){
					if($val!=''&&$val!=$model->pic1&&$val!=$model->pic2&&$val!=$model->pic3)
						@unlink(Yii::app()->basePath.'/../'.$val);
				}
				if($logo!=''&&$logo!=$model->logo)
					@unlink(Yii::app()->basePath.'/../'.$logo);
				Yii::app()->session['linkman']=$model->linkman;
				$this->redirect(array('my_jiajia','mess'=>'更新成功!'));
			}
		}
		$this->render('update',array('model'=>$model,'areas'=>$areas,'sorts'=>$sorts_model));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'list' page.
	 */
	public function actionDelete()
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadBusiness()->delete();
			$this->redirect(array('list'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$criteria=new CDbCriteria;

		$pages=new CPagination(Business::model()->count($criteria));
		$pages->pageSize=self::PAGE_SIZE;
		$pages->applyLimit($criteria);

		$sort=new CSort('Business');
		$sort->applyOrder($criteria);

		$models=Business::model()->findAll($criteria);

		$this->render('admin',array(
			'models'=>$models,
			'pages'=>$pages,
			'sort'=>$sort,
		));
	}
	
	public function actionUploadedFiles()
	{
		$state=$this->uploadfile('filedata');
		echo json_encode($state);
	}
	
	function uploadfile($inputname)
	{
		$mode=isset($_GET['mode'])?$_GET['mode']:'business';
		$mode_times="upload_{$mode}_times";
		
		$times=isset(Yii::app()->session[$mode_times])?Yii::app()->session[$mode_times]:0;
		if($times>=Yii::app()->params[$mode_times])
			return array('err'=>'一次性最多上传'.Yii::app()->params[$mode_times].'次图片,如仍需继续上传请提交信息后修改信息,或刷新本页进行上传.','msg'=>'');
		Yii::app()->session[$mode_times]=++$times;
			
		$immediate=isset($_GET['immediate'])?$_GET['immediate']:0;
		$attachdir='upload/temp/'.$mode;//上传文件保存路径，结尾不要带/
		$dirtype=1;//1:按天存入目录 2:按月存入目录 3:按扩展名存目录  建议使用按天存
		$maxattachsize=Yii::app()->params["upload_{$mode}_size"][0];//最大上传大小
		$maxsizemsg=Yii::app()->params["upload_{$mode}_size"][1];
		$upext='txt,rar,zip,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid';//上传扩展名
		$msgtype=2;//返回上传参数的格式：1，只返回url，2，返回参数数组
	
		$err = "";
		$msg = "";
		if(!isset($_FILES[$inputname]))return array('err'=>'文件域的name错误或者没选择文件','msg'=>$msg);
		$upfile=$_FILES[$inputname];
		if(!empty($upfile['error']))
		{
			switch($upfile['error'])
			{
				case '1':
					$err = '文件大小超过了php.ini定义的upload_max_filesize值';
					break;
				case '2':
					$err = '文件大小超过了HTML定义的MAX_FILE_SIZE值';
					break;
				case '3':
					$err = '文件上传不完全';
					break;
				case '4':
					$err = '无文件上传';
					break;
				case '6':
					$err = '缺少临时文件夹';
					break;
				case '7':
					$err = '写文件失败';
					break;
				case '8':
					$err = '上传被其它扩展中断';
					break;
				case '999':
				default:
					$err = '无有效错误代码';
			}
		}
		elseif(empty($upfile['tmp_name']) || $upfile['tmp_name'] == 'none')$err = '无文件上传';
		else
		{
			$temppath=$upfile['tmp_name'];
			$fileinfo=pathinfo($upfile['name']);
			$extension=$fileinfo['extension'];
			if(preg_match('/'.str_replace(',','|',$upext).'/i',$extension))
			{
				$filesize=filesize($temppath);
				if($filesize > $maxattachsize)$err='文件大小超过'.$maxsizemsg.'字节';
				else
				{
					switch($dirtype)
					{
						case 1: $attach_subdir = date('Y').'/'.date('m').'/'.date('d'); break;
						case 2: $attach_subdir = 'month_'.date('ym'); break;
						case 3: $attach_subdir = 'ext_'.$extension; break;
					}
					$attach_dir = $attachdir.'/'.$attach_subdir;
					if(!is_dir($attach_dir))
					{
						@mkdir($attach_dir, 0777,true);
						@fclose(fopen($attach_dir.'/index.htm', 'w'));
					}
				PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
				$filename=date("YmdHis").mt_rand(1000,9999).'.'.$extension;
				$target = $attach_dir.'/'.$filename;
				
				move_uploaded_file($upfile['tmp_name'],$target);
				if($immediate=='1')$target='!'.$target;
				if($msgtype==1)$msg=$target;
				else $msg=array('url'=>$target,'localname'=>$upfile['name'],'id'=>'1');//id参数固定不变，仅供演示，实际项目中可以是数据库ID
			}
		}
		else $err='上传文件扩展名必需为：'.$upext;

		@unlink($temppath);
	}
	return array('err'=>$err,'msg'=>$msg);
	}
	
	public function actionGet_next_area(){
		if(!Yii::app()->request->isAjaxRequest||!isset($_POST['code'])) return;
		$code=$_POST['code'];
		$sql="select code,name from areas where parent_code=$code and state=0"; 
		$models=Areas::model()->findAllBySql($sql);
		$json=array();
		foreach($models as $val){
			$json[]=array('code'=>$val->code,'name'=>$val->name);
		}
		echo CJSON::encode($json);
	}
	
	public function actionTest(){
		$model=new Business;
		$this->render('test',array('model'=>$model));
	}
	
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the primary key value. Defaults to null, meaning using the 'id' GET variable
	 */
	public function loadBusiness($id=null)
	{
		if($this->_model===null)
		{
			$criteria=new CDbCriteria();
			$criteria->select='business.*,areas.name as area_name,city.name as city_name,province.name as province_name';
			$criteria->join='INNER JOIN areas ON business.area=areas.code
							INNER JOIN areas as city ON left(business.area,4)=city.code
							INNER JOIN areas as province ON left(business.area,2)=province.code';
			$criteria->addCondition('business.id='.$id);
			$this->_model=Business::model()->find($criteria);
			if(!empty($this->_model)) $this->_model->product_sort=explode(",",$this->_model->product_sort);
			if($this->_model===null)
				throw new CHttpException(404,'The requested page does not exist.');
		}
		return $this->_model;
	}

	public function actionIsUniqueUsername(){
		if(Yii::app()->request->isAjaxRequest) {
			if(isset($_GET['Business']['username'])){
				$b=!Business::model()->exists(array('condition'=>'username=:username and state<>:state',
											'params'=>array(':username'=>$_GET['Business']['username'],':state'=>1)));
				echo $b?'true':'false';
			}
		}
	}
}
